﻿using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Xioa_UI.Attribute;

namespace Xioa_UI.Service;

public static class RegisterServices
{
    /// <summary>
    /// Service Attribute And Ioc Used
    /// </summary>
    /// <param name="services"></param>
    public static void RegisterAllServices(this Microsoft.Extensions.DependencyInjection.IServiceCollection services)
    {
        var thisAssembly = Assembly.GetEntryAssembly();
        var assemblies = thisAssembly!.GetReferencedAssemblies();
        var types = assemblies.Select(Assembly.Load)
            .Concat(new List<Assembly> { thisAssembly })
            .SelectMany(x => x.GetTypes())
            .Distinct();
        var wpfServicesClass = types.Where(e =>
                e.IsClass && e.GetCustomAttributes()
                    .Any(v => v.GetType() == typeof(ServiceAttribute)) 
        );
        foreach (var item in wpfServicesClass)
        {
            var attributeType = item.GetCustomAttribute(typeof(ServiceAttribute), true) as ServiceAttribute;
            
            if (attributeType is { Status: DataOrigin.Sequence.Singleton })
            {
                services.AddSingleton(item);
            }

            if (attributeType is { Status: DataOrigin.Sequence.Transient })
            {
                services.AddTransient(item);
            }

            if (attributeType is { Status: DataOrigin.Sequence.Scoped })
            {
                services.AddScoped(item);
            }
        }
    }
}